<?php
namespace App\Controllers\Admin\System;

use App\Components\Admin\ResponseHelper;
use App\Components\Twig\Twig;
use App\Models\System\SystemConfig;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

/**
 * 系统设置
 */
class ConfigController
{
    /**
     * 系统设置
     * @menu
     * @auth
     */
    public function system(Request $request, Response $response)
    {
        $listRs = SystemConfig::select('id', 'name', 'content')
            ->where('type', 'system')
            ->orderBy('id', 'asc')->get()->toArray();
        if ($request->getMethod() == 'POST') {
            $params = $request->getParsedBody();
            $params = array_filter($params);
            if (!isset($params['admin_name'])) {
                return ResponseHelper::error($response, '请填写管理程序名称');
            }
            if (!isset($params['admin_version'])) {
                return ResponseHelper::error($response, '请填写管理程序版本号');
            }
            unset($params['filepond']);
            foreach ($params as $k => $v) {
                $id = 0;
                foreach ($listRs as $v1) {
                    if ($k == $v1['name']) {
                        $id = $v1['id'];
                        break;
                    }
                }
                if ($id == 0) {
                    $insertRs = SystemConfig::insert([
                        'type' => 'system',
                        'name' => $k,
                        'content' => $v,
                        'created_at' => date('Y-m-d H:i:s'),
                    ]);
                    if ($insertRs != 1) {
                        return ResponseHelper::error($response, '设置项' . $k . '插入错误');
                    }
                } else {
                    SystemConfig::where('id', $id)
                        ->where('type', 'system')
                        ->where('name', $k)->update(['content' => $v]);
                }
            }

            SystemConfig::clearConfigCache('system');

            return ResponseHelper::success($response);
        }
        $list = [];
        foreach ($listRs as $v) {
            $list[$v['name']] = $v['content'];
        }
        unset($listRs);

        $view = Twig::fromRequest($request);
        $response->getBody()->write($view->fetch('admin/system/config/system.html', [
            'title' => '系统设置',
            'info' => $list,
        ]));
        return $response;
    }
}
